package com.mjp.learn.multi.juc;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * CountDownLatch 倒计时器
 * 相当于一个门闩,不让里面的线程跑出来，等待所有的线程完成了再继续执行
 */
public class Demo05 implements Runnable {
    public final static CountDownLatch end = new CountDownLatch(10);

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + " start check at :" + LocalDateTime.now().toString());
            Thread.sleep(new Random().nextInt(10) * 1000);
            System.out.println(Thread.currentThread().getName() + " check completed at :" + LocalDateTime.now().toString());
            end.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Demo05 demo = new Demo05();

        ExecutorService exec = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            exec.execute(demo);
        }

        try {
            end.await();
            System.out.println("all threads check completed, fire on");
            exec.shutdown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
